﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VOL.Core.Utilities;
using VOL.Domain.Infrastructure;
using VOL.Domain.IServices.SchedulingManagement;
using VOL.Entity.DomainModels;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using VOL.Entity.DomainModels.SchedulingManagement;

namespace VOL.Domain.Services.SchedulingManagement
{
    public class ShiftplanningService : IShiftplanningService
    {
        private readonly IBaseRepository<Shiftplanning> _repository;
        private readonly IBaseRepository<TeamTypeModel> _teamTypeRepository;

        public ShiftplanningService(
            IBaseRepository<Shiftplanning> repository,
            IBaseRepository<TeamTypeModel> teamTypeRepository)
        {
            _repository = repository;
            _teamTypeRepository = teamTypeRepository;
        }

        public async Task<WebResponseContent> BatchAddShiftplannings(List<Shiftplanning> shiftplannings)
        {
            var response = new WebResponseContent();

            if (shiftplannings == null || !shiftplannings.Any())
            {
                return response.Error("请提供要添加的排班计划数据");
            }

            try
            {
                // 检查是否有重复的计划编号
                var shiftCodes = shiftplannings.Select(x => x.ShiftCode).ToList();

                var existingPlans = await _repository.GetAll()
                    .Where(x => shiftCodes.Contains(x.ShiftCode))
                    .ToListAsync();

                if (existingPlans.Any())
                {
                    return response.Error("存在重复的计划编号，请检查数据");
                }

                foreach (var plan in shiftplannings)
                {
                    await _repository.Add(plan);
                }

                return response.OK("批量添加成功");
            }
            catch (Exception ex)
            {
                return response.Error("批量添加失败：" + ex.Message);
            }
        }

        public async Task<WebResponseContent> BatchDeleteShiftplannings(int[] ids)
        {
            var response = new WebResponseContent();

            if (ids == null || ids.Length == 0)
            {
                return response.Error("请选择要删除的记录");
            }

            try
            {
                var plans = await _repository.GetAll()
                    .Where(x => ids.Contains(x.id))
                    .ToListAsync();

                if (!plans.Any())
                {
                    return response.Error("未找到要删除的记录");
                }

                foreach (var plan in plans)
                {
                    await _repository.Delete(plan);
                }

                return response.OK($"成功删除{plans.Count}条记录");
            }
            catch (Exception ex)
            {
                return response.Error("批量删除失败：" + ex.Message);
            }
        }

        public async Task<WebResponseContent> UpdateShiftplanning(Shiftplanning shiftplanning)
        {
            var response = new WebResponseContent();

            if (shiftplanning == null || shiftplanning.id <= 0)
            {
                return response.Error("无效的排班计划数据");
            }

            try
            {
                var existingPlan = await _repository.GetAll()
                    .FirstOrDefaultAsync(x => x.id == shiftplanning.id);

                if (existingPlan == null)
                {
                    return response.Error("未找到要更新的排班计划");
                }

                // 检查是否存在重复的计划编号（排除当前记录）
                var duplicatePlan = await _repository.GetAll()
                    .FirstOrDefaultAsync(x => x.ShiftCode == shiftplanning.ShiftCode 
                        && x.id != shiftplanning.id);

                if (duplicatePlan != null)
                {
                    return response.Error("该计划编号已存在");
                }

                // 更新实体属性
                existingPlan.ShiftCode = shiftplanning.ShiftCode;
                existingPlan.ShiftName = shiftplanning.ShiftName;
                existingPlan.TeamType = shiftplanning.TeamType;
                existingPlan.BeginTime = shiftplanning.BeginTime;
                existingPlan.EndTime = shiftplanning.EndTime;
                existingPlan.Shiftmodel = shiftplanning.Shiftmodel;
                existingPlan.Pourmodel = shiftplanning.Pourmodel;
                existingPlan.Documentstatus = shiftplanning.Documentstatus;
                existingPlan.RemarkText = shiftplanning.RemarkText;

                await _repository.Update(existingPlan);
                return response.OK("更新成功");
            }
            catch (Exception ex)
            {
                return response.Error("更新失败：" + ex.Message);
            }
        }

        public async Task<WebResponseContent> GetShiftplanningList()
        {
            var response = new WebResponseContent();

            try
            {
                // 联表查询排班计划和班组类型
                var query = from s in _repository.GetAll()
                           join t in _teamTypeRepository.GetAll() on s.TeamType equals t.TeamType into teamJoin
                           from tj in teamJoin.DefaultIfEmpty()
                           select new ShiftplanningDTO
                           {
                               id = s.id,
                               ShiftCode = s.ShiftCode,
                               ShiftName = s.ShiftName,
                               TeamType = s.TeamType,
                               TeamTypeName = tj.TeamTypeName ?? "",  // 班组类型名称
                               BeginTime = s.BeginTime,
                               EndTime = s.EndTime,
                               Shiftmodel = s.Shiftmodel,
                               Pourmodel = s.Pourmodel,
                               Documentstatus = s.Documentstatus,
                               RemarkText = s.RemarkText,
                           };

                var list = await query
                    .OrderByDescending(x => x.BeginTime)
                    .ThenBy(x => x.ShiftCode)
                    .ToListAsync();

                return response.OK(null, list);
            }
            catch (Exception ex)
            {
                return response.Error("获取数据失败：" + ex.Message);
            }
        }
    }
}
